#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

function color_msg() {
    case "$1" in
    "error" | "red")
        echo -e "\e[1;31m$2\e[0m"
        ;;
    "warn" | "yellow")
        echo -e "\e[1;33m$2\e[0m"
        ;;
    "success" | "green")
        echo -e "\e[1;32m$2\e[0m"
        ;;
    "info" | "blue")
        echo -e "\e[1;34m$2\e[0m"
        ;;
    esac
}

# 判断是否root用户
if [ $(id -u) -ne 0 ]; then
    color_msg error "### This script must be run as root !!!"
    exit 1
fi

# 判断是否有足够的参数
if [ $# -lt 1 ]; then

    color_msg green "\n\tUsage:  bash <(curl -sL http://wuyou.run/go/install.sh) openresty \n"

    color_msg error "List of Support Services:"
    curl -s http://wuyou.run/services/ | grep ".sh" | awk -F'[<>]' '{print $3}' | awk -F'.sh' '{print $1}' | grep -v "install"
    exit 1
fi

now=$(date +%Y%m%d%H%M%S) # 获取当前时间

echo "*****************************************"
color_msg info ">> 开始执行 ... $1"
echo "*****************************************"

######################################################################
# 安装流程
######################################################################

function DoInstall() {
    $1
    if [ $? -eq 0 ]; then
        echo "*****************************************"
        color_msg blue ">> 执行 $1 success."
        echo "*****************************************"
    else
        echo "*****************************************"
        color_msg error ">> 执行 $1 failed."
        echo "*****************************************"
        exit 1
    fi
}

function main() {

    # 检查服务文件是否存在
    if ! curl -sI http://wuyou.run/services/"$service_file" | grep -q "200 OK"; then
        color_msg error "### Service '$1' not found !!!"
        exit 1
    fi

    # 下载并执行服务安装脚本
    curl -s http://wuyou.run/services/"$1".sh | bash
}

# 删除历史日志
rm install.*.log -f >/dev/null 2>&1 &

main $1 | tee "$1.install.$(date +%Y%m%d%H%M%S).log"
echo ">> Log: $1.install.$(date +%Y%m%d%H%M%S).log"
